// 会员服务 - 管理会员状态和相关操作，与后端API交互

class MemberService {
  constructor() {
    this.memberStatus = null
    this.memberExpiryDate = null
    this.autoRenew = false
    this.apiBaseUrl = '/api' // 后端API基础路径
  }
  
  // 通用请求方法，带认证
  async request(endpoint, options = {}) {
    const url = `${this.apiBaseUrl}${endpoint}`;
    const token = localStorage.getItem('token');
    
    const defaultOptions = {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
      },
    };

    const mergedOptions = {
      ...defaultOptions,
      ...options,
      headers: {
        ...defaultOptions.headers,
        ...options.headers,
      },
    };

    try {
      const response = await fetch(url, mergedOptions);
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || errorData.msg || `HTTP错误! 状态: ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      console.warn('会员API请求失败:', error);
      // 返回空对象而不是抛出错误，这样前端应用可以继续运行
      return {};
    }
  }

  // 初始化会员服务
  async init() {
    await this.refreshMemberStatus()
    // 定期检查会员状态
    setInterval(() => {
      this.refreshMemberStatus().catch(error => {
        console.error('定期刷新会员状态失败:', error)
      })
    }, 300000) // 每5分钟检查一次
  }

  // 从localStorage加载会员状态（本地缓存）
  loadMemberStatus() {
    try {
      const user = localStorage.getItem('user')
      if (user) {
        const parsedUser = JSON.parse(user)
        this.memberStatus = parsedUser.isMember || false
        this.memberExpiryDate = parsedUser.memberExpiryDate
        this.autoRenew = parsedUser.autoRenew !== false // 默认开启自动续费
        
        // 检查会员是否过期
        if (this.memberStatus && this.memberExpiryDate) {
          const expiryDate = new Date(this.memberExpiryDate)
          const now = new Date()
          if (expiryDate < now) {
            this.updateMemberStatus(false)
            console.log('会员已过期')
          } else {
            // 检查是否需要提醒续费（到期前3天）
            const daysUntilExpiry = Math.ceil((expiryDate - now) / (1000 * 60 * 60 * 24))
            if (daysUntilExpiry <= 3) {
              this.showRenewalReminder(daysUntilExpiry)
            }
          }
        }
      }
    } catch (error) {
      console.error('加载会员状态失败:', error)
      this.memberStatus = false
    }
    return this.memberStatus
  }
  
  // 从后端刷新会员状态
  async refreshMemberStatus() {
    try {
      // 确保用户已登录
      if (!localStorage.getItem('token')) {
        this.memberStatus = false
        return false
      }
      
      const response = await this.request('/member/info')
      const memberData = response.data || response
      
      if (memberData && Object.keys(memberData).length > 0) {
        this.memberStatus = memberData.status === 1
        this.memberExpiryDate = memberData.endDate
        this.autoRenew = memberData.autoRenew === 1
        
        // 更新本地用户信息
        this.updateLocalMemberInfo(this.memberStatus, this.memberExpiryDate, this.autoRenew)
        
        // 触发会员状态变更事件
        this.triggerMemberStatusChange()
      }
      
      return this.memberStatus
    } catch (error) {
      console.warn('刷新会员状态失败:', error)
      // 失败时回退到本地缓存
      return this.loadMemberStatus()
    }
  }
  
  // 更新本地存储的会员信息
  updateLocalMemberInfo(isMember, expiryDate = null, autoRenew = true) {
    try {
      const user = localStorage.getItem('user')
      if (user) {
        const parsedUser = JSON.parse(user)
        parsedUser.isMember = isMember
        parsedUser.memberExpiryDate = expiryDate
        parsedUser.autoRenew = autoRenew
        localStorage.setItem('user', JSON.stringify(parsedUser))
      }
    } catch (error) {
      console.error('更新本地会员信息失败:', error)
    }
  }

  // 更新会员状态
  updateMemberStatus(isMember, expiryDate = null, autoRenew = true) {
    try {
      const user = localStorage.getItem('user')
      if (user) {
        const parsedUser = JSON.parse(user)
        parsedUser.isMember = isMember
        parsedUser.memberExpiryDate = expiryDate
        parsedUser.autoRenew = autoRenew
        localStorage.setItem('user', JSON.stringify(parsedUser))
        
        this.memberStatus = isMember
        this.memberExpiryDate = expiryDate
        this.autoRenew = autoRenew
        
        // 触发会员状态变更事件
        this.triggerMemberStatusChange()
        
        return true
      }
    } catch (error) {
      console.error('更新会员状态失败:', error)
    }
    return false
  }

  // 获取会员套餐列表
  async getMemberPackages() {
    try {
      const response = await this.request('/api/member/packages')
      return response.data || response
    } catch (error) {
      console.error('获取会员套餐失败:', error)
      throw error
    }
  }
  
  // 开通/续费会员
  async subscribe(packageId) {
    try {
      const response = await this.request('/api/member/subscribe', {
        method: 'POST',
        body: JSON.stringify({ packageId })
      })
      
      const result = response.data || response
      if (result.member) {
        this.memberStatus = true
        this.memberExpiryDate = result.member.endDate
        this.updateLocalMemberInfo(true, result.member.endDate, result.member.autoRenew === 1)
        this.triggerMemberStatusChange()
      }
      
      return result
    } catch (error) {
      console.error('开通/续费会员失败:', error)
      throw error
    }
  }
  
  // 取消自动续费
  async cancelAutoRenew() {
    try {
      const response = await this.request('/api/member/cancel-auto-renew', {
        method: 'POST'
      })
      
      this.autoRenew = false
      this.updateLocalMemberInfo(this.memberStatus, this.memberExpiryDate, false)
      
      return true
    } catch (error) {
      console.error('取消自动续费失败:', error)
      throw error
    }
  }
  
  // 获取支付记录
  async getPaymentRecords() {
    try {
      const response = await this.request('/api/member/payment-records')
      return response.data || response
    } catch (error) {
      console.error('获取支付记录失败:', error)
      throw error
    }
  }

  // 显示续费提醒
  showRenewalReminder(days) {
    // 避免重复显示提醒
    const lastReminderKey = 'lastRenewalReminder'
    const lastReminder = localStorage.getItem(lastReminderKey)
    const today = new Date().toDateString()
    
    if (lastReminder !== today) {
      // 显示温柔的续费提示
      const message = `您的情绪陪伴即将到期，还有${days}天。续费继续享受专属关怀，不要让这份温暖中断～`
      console.log(message)
      
      // 可以在这里触发UI提示
      if (typeof window !== 'undefined' && window.showToast) {
        window.showToast(message, 'info')
      }
      
      localStorage.setItem(lastReminderKey, today)
    }
  }

  // 获取会员状态
  isMember() {
    if (this.memberStatus === null) {
      this.loadMemberStatus()
    }
    return this.memberStatus
  }

  // 获取会员到期时间
  getExpiryDate() {
    if (!this.memberExpiryDate) {
      this.loadMemberStatus()
    }
    return this.memberExpiryDate
  }

  // 检查是否可以使用某项会员功能
  canUseFeature(feature) {
    // 免费功能列表
    const freeFeatures = ['basic-diary', 'basic-emotion-analysis', 'basic-anonymous-chat']
    
    if (freeFeatures.includes(feature)) {
      return true
    }
    
    // 付费功能需要会员
    return this.isMember()
  }

  // 触发会员状态变更事件
  triggerMemberStatusChange() {
    // 这里可以使用事件总线或发布订阅模式通知其他组件
    console.log('会员状态已变更:', this.memberStatus)
  }

  // 格式化会员到期时间显示
  formatExpiryDate() {
    if (!this.memberExpiryDate) return '未开通'
    
    const date = new Date(this.memberExpiryDate)
    const now = new Date()
    const diffTime = date - now
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    
    if (diffDays <= 0) {
      return '已过期'
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day} (剩余${diffDays}天)`
  }
}

// 导出单例实例
const memberService = new MemberService()
export default memberService

// 在应用启动时初始化
export function initMemberService() {
  memberService.init()
}